/*
 * Copyright (c) 2024 Shenzhen Kaihong Digital Industry Development Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "sle_adapter_state_machine.h"
#include "sle_adapter_manager.h"
#include "sle_host_service.h"
#include "sle_hilog.h"

namespace OHOS {
namespace NearLink {
namespace SleStandard {
SleErrorCode SleAdapterStateMachine::Initialize()
{
	std::unique_ptr<State> turningOn = std::make_unique<TurningOn>(*this, TURNING_ON_STATE);
    SLE_ASSERT_AND_RETURN_RET_LOG(turningOn, SLE_ERR_NOT_READY, "create turning on failed!");
    SLE_ASSERT_AND_RETURN_RET_LOG(Move(turningOn), SLE_ERR_NOT_READY, "add turning on state failed!");

	std::unique_ptr<State> turnOn = std::make_unique<TurnOn>(*this, TURN_ON_STATE);
    SLE_ASSERT_AND_RETURN_RET_LOG(turnOn, SLE_ERR_NOT_READY, "create turn on failed!");
    SLE_ASSERT_AND_RETURN_RET_LOG(Move(turnOn), SLE_ERR_NOT_READY, "add turn on state failed!");

	std::unique_ptr<State> turningOff = std::make_unique<TurningOff>(*this, TURNING_OFF_STATE);
    SLE_ASSERT_AND_RETURN_RET_LOG(turningOff, SLE_ERR_NOT_READY, "create turning off failed!");
    SLE_ASSERT_AND_RETURN_RET_LOG(Move(turningOff), SLE_ERR_NOT_READY, "add turning off state failed!");

	std::unique_ptr<State> turnOff = std::make_unique<TurnOff>(*this, TURN_OFF_STATE);
    SLE_ASSERT_AND_RETURN_RET_LOG(turnOff, SLE_ERR_NOT_READY, "create turn off failed!");
    SLE_ASSERT_AND_RETURN_RET_LOG(Move(turnOff), SLE_ERR_NOT_READY, "add turn off state failed!");

    SLE_ASSERT_AND_RETURN_RET_LOG(InitState(TURN_OFF_STATE), SLE_ERR_NOT_READY, "init sle state failed!");
    return SLE_NO_ERROR;
}

TurningOn::TurningOn(SleAdapterStateMachine &stateMachine, const std::string &name)
    : State(name), adapterStateMachine_(stateMachine)
{
    adapterTimer_ = std::make_unique<Timer>([&]() {
        stateMachine.ProcessMessage(SleAdapterStateMessage::MSG_ADAPTER_ENABLE_TIMEOUT);
    });
}

bool TurningOn::Entry()
{
    SLE_LOGD("TurningOn state entry");
    if (adapterTimer_ == nullptr) {
        return false;
    }
    if (adapterTimer_ != nullptr) {
        adapterTimer_->Start(SLE_ENABLE_DISABLE_TIMEOUT_TIME, false);
    } else {
        adapterStateMachine_.Transition(TURN_OFF_STATE);
        return false;
    }
    SleErrorCode ret = SleHostService::GetInstance()->EnableSle();
    if (ret != SLE_NO_ERROR) {
        if (adapterTimer_ != nullptr) {
            adapterTimer_->Stop();
        }
        adapterStateMachine_.Transition(TURN_OFF_STATE);
        return false;
    }
    return true;
}

void TurningOn::Exit()
{
    SLE_LOGD("TurningOn state exit");
}

bool TurningOn::Dispatch(const Message &msg)
{
    switch (msg.what_) {
        case SleAdapterStateMessage::MSG_ADAPTER_ENABLE_CMP:
            if (adapterTimer_ != nullptr) {
                adapterTimer_->Stop();
            }
            if (msg.arg1_) {
                adapterStateMachine_.Transition(TURN_ON_STATE);
            } else {
                adapterStateMachine_.Transition(TURN_OFF_STATE);
            }
            break;
        case SleAdapterStateMessage::MSG_ADAPTER_ENABLE_TIMEOUT:
            SLE_LOGE("enable sle timeout error!");
            adapterStateMachine_.Transition(TURN_OFF_STATE);
            break;
        default:
            return false;
    }
    return true;
}

bool TurnOn::Entry()
{
    SLE_LOGD("TurnOn state entry");
    int result = adapterStateMachine_.GetLastState()->Name().compare(TURNING_ON_STATE);
    if (result == SLE_NO_ERROR) {
        SleAdapterManager::GetInstance()->OnSleStateChange(SLE_HOST_STATE_ENABLED);
    }
    return true;
}

void TurnOn::Exit()
{
    SLE_LOGD("TurnOn state exit");
}

bool TurnOn::Dispatch(const Message &msg)
{
    switch (msg.what_) {
        case SleAdapterStateMessage::MSG_ADAPTER_DISABLE_REQ:
            return adapterStateMachine_.Transition(TURNING_OFF_STATE);
        default:
            return false;
    }
}

TurningOff::TurningOff(SleAdapterStateMachine &stateMachine, const std::string &name)
    : State(name), adapterStateMachine_(stateMachine)
{
    adapterTimer_ = std::make_unique<Timer>([&]() {
        stateMachine.ProcessMessage(SleAdapterStateMessage::MSG_ADAPTER_DISABLE_TIMEOUT);
    });
}

bool TurningOff::Entry()
{
    SLE_LOGD("TurningOff state entry");
    if (adapterTimer_ == nullptr) {
        return false;
    }
    if (adapterTimer_ != nullptr) {
        adapterTimer_->Start(SLE_ENABLE_DISABLE_TIMEOUT_TIME, false);
    } else {
        adapterStateMachine_.Transition(TURN_ON_STATE);
        return false;
    }
    int32_t ret = SleHostService::GetInstance()->DisableSle();
    if (ret != SLE_NO_ERROR) {
        if (adapterTimer_ != nullptr) {
            adapterTimer_->Stop();
        }
        adapterStateMachine_.Transition(TURN_ON_STATE);
        return false;
    }
    return true;
}

void TurningOff::Exit()
{
    SLE_LOGD("TurningOff state exit");
}

bool TurningOff::Dispatch(const Message &msg)
{
    switch (msg.what_) {
        case SleAdapterStateMessage::MSG_ADAPTER_DISABLE_CMP:
            if (adapterTimer_ != nullptr) {
                adapterTimer_->Stop();
            }
            if (msg.arg1_) {
                adapterStateMachine_.Transition(TURN_OFF_STATE);
            } else {
                adapterStateMachine_.Transition(TURN_ON_STATE);
            }
            break;
        case SleAdapterStateMessage::MSG_ADAPTER_DISABLE_TIMEOUT:
            SLE_LOGE("disable sle timeout error!");
            adapterStateMachine_.Transition(TURN_ON_STATE);
            break;
        default:
            return false;
    }
    return true;
}

bool TurnOff::Entry()
{
    SLE_LOGD("TurnOff state entry");
    int result = adapterStateMachine_.GetLastState()->Name().compare(TURNING_OFF_STATE);
    if (result == SLE_NO_ERROR) {
        SleAdapterManager::GetInstance()->OnSleStateChange(SLE_HOST_STATE_DISABLED);
    }
    return true;
}

void TurnOff::Exit()
{
    SLE_LOGD("TurnOff state exit");
}

bool TurnOff::Dispatch(const Message &msg)
{
    switch (msg.what_) {
        case SleAdapterStateMessage::MSG_ADAPTER_ENABLE_REQ:
            return adapterStateMachine_.Transition(TURNING_ON_STATE);
        default:
            return false;
    }
}
} // SleStandard
} // NearLink
} // OHOS